import React, { useState, useEffect, useMemo } from 'react';
import { Dormitory, DormitoryMember, mockDormitories } from '../mock/dormitoryData';
import { Student, mockStudents } from '../mock/studentData';
import { getDormitories, addDormitory, updateDormitory, deleteDormitory, getDormitoryBuildings } from '../mock/dormitoryData';

// 定义值日表类型
interface DutySchedule {
  [day: string]: string[]; // 每天的值日生列表（学生ID）
}

// 扩展宿舍接口以包含值日表
interface DormitoryWithDuty extends Dormitory {
  dutySchedule?: DutySchedule;
}

// 定义表单数据类型
interface DormitoryFormData extends Omit<DormitoryWithDuty, 'id'> {}

/**
 * 宿舍管理组件
 * 提供宿舍信息的增删改查功能以及成员管理功能
 */
const DormitoryManagement: React.FC = () => {
  const [dormitories, setDormitories] = useState<DormitoryWithDuty[]>([]);
  const [buildings, setBuildings] = useState<string[]>([]);
  const [students, setStudents] = useState<Student[]>([]);
  const [isModalVisible, setIsModalVisible] = useState(false);
  const [isEditMode, setIsEditMode] = useState(false);
  const [isMemberModalVisible, setIsMemberModalVisible] = useState(false);
  const [currentDormitory, setCurrentDormitory] = useState<DormitoryWithDuty | null>(null);
  const [formData, setFormData] = useState<DormitoryFormData>({
    buildingName: '',
    roomNumber: '',
    capacity: 4, // 设置默认容量为4人
    members: [],
    gender: '男',
    dutySchedule: {
      '周一': [],
      '周二': [],
      '周三': [],
      '周四': [],
      '周五': [],
      '周六': [],
      '周日': []
    }
  });
  const [loading, setLoading] = useState(true);
  const [filterBuilding, setFilterBuilding] = useState<string>('');
  const [filterGender, setFilterGender] = useState<string>(''); // 新增：按性别筛选
  const [filterStatus, setFilterStatus] = useState<string>(''); // 新增：按入住状态筛选
  const [searchTerm, setSearchTerm] = useState<string>(''); // 新增：搜索关键词
  const [currentPage, setCurrentPage] = useState<number>(1); // 新增：当前页码
  const [pageSize, setPageSize] = useState<number>(10); // 新增：每页显示数量
  const [formErrors, setFormErrors] = useState<Record<string, string>>({});
  const [availableStudents, setAvailableStudents] = useState<Student[]>([]);
  const [selectedClass, setSelectedClass] = useState<string>(''); // 存储所选班级
  const [uniqueClasses, setUniqueClasses] = useState<string[]>([]); // 存储所有唯一的班级

  // 获取宿舍数据
  const fetchDormitories = async () => {
    setLoading(true);
    try {
      const data = await getDormitories();
      setDormitories(data);
    } catch (error) {
      console.error('获取宿舍数据失败:', error);
      alert('获取宿舍数据失败: ' + (error instanceof Error ? error.message : '未知错误'));
    } finally {
      setLoading(false);
    }
  };

  // 获取宿舍楼数据
  const fetchBuildings = async () => {
    try {
      const buildingData = await getDormitoryBuildings();
      const buildingNames = [...new Set(buildingData.map(building => building.name))];
      setBuildings(buildingNames);
    } catch (error) {
      console.error('获取宿舍楼数据失败:', error);
    }
  };

  // 获取学生数据
  const fetchStudents = async () => {
    try {
      // 使用导入的模拟学生数据
      setStudents(mockStudents);
    } catch (error) {
      console.error('获取学生数据失败:', error);
    }
  };

  // 按班级分配学生到宿舍
  const assignStudentsByClass = async (className: string) => {
    if (!currentDormitory) return;

    try {
      // 过滤出指定班级且未分配宿舍的学生
      const assignedStudentIds = dormitories.flatMap(d => d.members.map(m => m.studentId));
      const classStudents = students.filter(student => 
        student.class === className && 
        student.gender === currentDormitory.gender && 
        !assignedStudentIds.includes(student.studentId) &&
        !formData.members.some(m => m.studentId === student.studentId)
      );

      if (classStudents.length === 0) {
        alert(`班级 ${className} 中没有可分配的学生`);
        return;
      }

      // 计算还能添加多少学生
      const availableSlots = formData.capacity - formData.members.length;
      if (availableSlots <= 0) {
        alert(`宿舍已满，无法添加学生`);
        return;
      }

      // 确定要添加的学生数量（不超过剩余容量）
      const studentsToAdd = classStudents.slice(0, availableSlots);
      
      // 添加学生到宿舍
      const newMembers = [...formData.members];
      studentsToAdd.forEach(student => {
        const newMember: DormitoryMember = {
          studentId: student.studentId,
          name: student.name,
          gender: student.gender,
          class: student.class
        };
        newMembers.push(newMember);
      });

      setFormData(prev => ({
        ...prev,
        members: newMembers
      }));

      // 更新可选学生列表
      const remainingAvailableStudents = availableStudents.filter(student => 
        !studentsToAdd.some(s => s.studentId === student.studentId)
      );
      setAvailableStudents(remainingAvailableStudents);

      alert(`成功从 ${className} 班级添加了 ${studentsToAdd.length} 名学生到宿舍`);
    } catch (error) {
      console.error('按班级分配学生失败:', error);
      alert('按班级分配学生失败: ' + (error instanceof Error ? error.message : '未知错误'));
    }
  };

  // 添加宿舍
  const addDormitoryAction = async (values: DormitoryFormData) => {
    try {
      const newDormitory = await addDormitory(values);
      setDormitories([...dormitories, newDormitory]);
      alert('添加宿舍成功');
      return true;
    } catch (error) {
      console.error('添加宿舍失败:', error);
      alert('添加宿舍失败: ' + (error instanceof Error ? error.message : '未知错误'));
      return false;
    }
  };

  // 更新宿舍
  const updateDormitoryAction = async (values: DormitoryFormData) => {
    if (!currentDormitory) return false;
    
    try {
      const updatedDormitory = await updateDormitory(currentDormitory.id, values);
      if (updatedDormitory) {
        const updatedDormitories = dormitories.map(dorm => 
          dorm.id === currentDormitory.id ? updatedDormitory : dorm
        );
        setDormitories(updatedDormitories);
        alert('更新宿舍成功');
        return true;
      }
      alert('更新宿舍失败: 宿舍不存在');
      return false;
    } catch (error) {
      console.error('更新宿舍失败:', error);
      alert('更新宿舍失败: ' + (error instanceof Error ? error.message : '未知错误'));
      return false;
    }
  };

  // 删除宿舍
  const deleteDormitoryAction = async (id: number) => {
    try {
      const success = await deleteDormitory(id);
      if (success) {
        const updatedDormitories = dormitories.filter(dorm => dorm.id !== id);
        setDormitories(updatedDormitories);
        alert('删除宿舍成功');
      } else {
        alert('删除宿舍失败: 宿舍不存在');
      }
    } catch (error) {
      console.error('删除宿舍失败:', error);
      alert('删除宿舍失败: ' + (error instanceof Error ? error.message : '未知错误'));
    }
  };

  // 显示添加模态框
  const showAddModal = () => {
    setIsEditMode(false);
    setFormData({
      buildingName: buildings[0] || '',
      roomNumber: '',
      capacity: 4, // 默认4人
      members: [],
      gender: '男',
      dutySchedule: {
        '周一': [],
        '周二': [],
        '周三': [],
        '周四': [],
        '周五': [],
        '周六': [],
        '周日': []
      }
    });
    setFormErrors({});
    setIsModalVisible(true);
  };

  // 显示编辑模态框
  const showEditModal = (dorm: Dormitory) => {
    setIsEditMode(true);
    setCurrentDormitory(dorm);
    setFormData({
      buildingName: dorm.buildingName,
      roomNumber: dorm.roomNumber,
      capacity: dorm.capacity,
      members: dorm.members,
      gender: dorm.gender,
      dutySchedule: dorm.dutySchedule || {
        '周一': [],
        '周二': [],
        '周三': [],
        '周四': [],
        '周五': [],
        '周六': [],
        '周日': []
      }
    });
    setFormErrors({});
    setIsModalVisible(true);
  };

  // 显示成员管理模态框
  const showMemberModal = (dorm: DormitoryWithDuty) => {
    setCurrentDormitory(dorm);
    setFormData({
      buildingName: dorm.buildingName,
      roomNumber: dorm.roomNumber,
      capacity: dorm.capacity,
      members: dorm.members,
      gender: dorm.gender,
      dutySchedule: dorm.dutySchedule || {
        '周一': [],
        '周二': [],
        '周三': [],
        '周四': [],
        '周五': [],
        '周六': [],
        '周日': []
      }
    });
    setSelectedClass(''); // 重置选择的班级
    
    // 过滤出可以添加的学生（同性别且未分配到其他宿舍）
    const assignedStudentIds = dormitories.flatMap(d => d.members.map(m => m.studentId));
    const available = students.filter(student => 
      student.gender === dorm.gender && 
      !assignedStudentIds.includes(student.studentId) &&
      // 排除当前宿舍已有的学生
      !dorm.members.some(m => m.studentId === student.studentId)
    );
    setAvailableStudents(available);
    
    // 获取所有同性别学生的唯一班级
    const sameGenderStudents = students.filter(s => s.gender === dorm.gender);
    const classes = [...new Set(sameGenderStudents.map(s => s.class))].sort();
    setUniqueClasses(classes);
    
    setIsMemberModalVisible(true);
  };

  // 处理表单输入变化
  const handleInputChange = (e: React.ChangeEvent<HTMLInputElement | HTMLSelectElement>) => {
    const { name, value } = e.target;
    setFormData(prev => ({
      ...prev,
      [name]: name === 'capacity' ? parseInt(value) || 8 : value
    }));
  };

  // 添加学生到宿舍
  const addStudentToDormitory = (student: Student) => {
    if (formData.members.length >= formData.capacity) {
      alert(`该宿舍已满员（${formData.capacity}人），无法添加更多学生`);
      return;
    }
    
    const newMember: DormitoryMember = {
      studentId: student.studentId,
      name: student.name,
      gender: student.gender,
      class: student.class
    };
    
    setFormData(prev => ({
      ...prev,
      members: [...prev.members, newMember]
    }));
    
    // 从可选列表中移除该学生
    setAvailableStudents(prev => prev.filter(s => s.studentId !== student.studentId));
  };

  // 从宿舍移除学生
  const removeStudentFromDormitory = (studentId: string) => {
    const removedStudent = formData.members.find(m => m.studentId === studentId);
    setFormData(prev => ({
      ...prev,
      members: prev.members.filter(m => m.studentId !== studentId)
    }));
    
    // 如果找到了被移除的学生，将其添加回可选列表
    if (removedStudent) {
      const fullStudent = students.find(s => s.studentId === studentId);
      if (fullStudent) {
        setAvailableStudents(prev => [...prev, fullStudent]);
      }
    }
  };

  // 保存成员更改
  const saveMemberChanges = async () => {
    if (!currentDormitory) return;
    
    try {
      const updatedDormitory = await updateDormitory(currentDormitory.id, {
        members: formData.members,
        dutySchedule: formData.dutySchedule
      });
      
      if (updatedDormitory) {
        const updatedDormitories = dormitories.map(dorm => 
          dorm.id === currentDormitory.id ? updatedDormitory : dorm
        );
        setDormitories(updatedDormitories);
        alert('成员管理成功');
        setIsMemberModalVisible(false);
      }
    } catch (error) {
      console.error('保存成员更改失败:', error);
      alert('保存成员更改失败: ' + (error instanceof Error ? error.message : '未知错误'));
    }
  };

  // 验证表单
  const validateForm = () => {
    const errors: Record<string, string> = {};
    
    if (!formData.buildingName.trim()) {
      errors.buildingName = '楼宇名称不能为空';
    }
    
    if (!formData.roomNumber.trim()) {
      errors.roomNumber = '房间号不能为空';
    }
    
    if (isNaN(formData.capacity) || formData.capacity <= 0 || formData.capacity > 4) {
      errors.capacity = '宿舍容量必须为1-4之间的整数';
    }
    
    if (formData.members.length > formData.capacity) {
      errors.members = `成员数量不能超过宿舍容量（${formData.capacity}人）`;
    }
    
    setFormErrors(errors);
    return Object.keys(errors).length === 0;
  };
  
  // 处理值日表更改
  const handleDutyScheduleChange = (day: string, studentId: string, checked: boolean) => {
    const updatedSchedule = { ...formData.dutySchedule };
    if (checked) {
      // 添加学生到值日表
      if (!updatedSchedule[day].includes(studentId)) {
        updatedSchedule[day] = [...updatedSchedule[day], studentId];
      }
    } else {
      // 从值日表移除学生
      updatedSchedule[day] = updatedSchedule[day].filter(id => id !== studentId);
    }
    
    setFormData(prev => ({
      ...prev,
      dutySchedule: updatedSchedule
    }));
  };

  // 处理表单提交
  const handleSubmit = async (e: React.FormEvent) => {
    e.preventDefault();
    if (validateForm()) {
      const success = isEditMode ? await updateDormitoryAction(formData) : await addDormitoryAction(formData);
      if (success) {
        setIsModalVisible(false);
      }
    }
  };

  // 处理表单取消
  const handleCancel = () => {
    setIsModalVisible(false);
    setIsMemberModalVisible(false);
    setFormErrors({});
  };

  // 过滤数据
  const filteredDormitories = React.useMemo(() => {
    let result = [...dormitories];
    
    // 按楼宇筛选
    if (filterBuilding) {
      result = result.filter(dorm => dorm.buildingName === filterBuilding);
    }
    
    // 按性别筛选
    if (filterGender) {
      result = result.filter(dorm => dorm.gender === filterGender);
    }
    
    // 按入住状态筛选
    if (filterStatus) {
      if (filterStatus === 'occupied') {
        result = result.filter(dorm => dorm.members.length > 0);
      } else if (filterStatus === 'empty') {
        result = result.filter(dorm => dorm.members.length === 0);
      }
    }
    
    // 按关键词搜索（房间号或楼宇名称）
    if (searchTerm) {
      const term = searchTerm.toLowerCase();
      result = result.filter(dorm => 
        dorm.roomNumber.toLowerCase().includes(term) || 
        dorm.buildingName.toLowerCase().includes(term)
      );
    }
    
    return result;
  }, [dormitories, filterBuilding, filterGender, filterStatus, searchTerm]);
  
  // 分页计算
  const paginatedDormitories = React.useMemo(() => {
    const startIndex = (currentPage - 1) * pageSize;
    const endIndex = startIndex + pageSize;
    return filteredDormitories.slice(startIndex, endIndex);
  }, [filteredDormitories, currentPage, pageSize]);
  
  // 计算总页数
  const totalPages = Math.ceil(filteredDormitories.length / pageSize);
  
  // 处理页码变化
  const handlePageChange = (page: number) => {
    if (page >= 1 && page <= totalPages) {
      setCurrentPage(page);
    }
  };
  
  // 处理每页显示数量变化
  const handlePageSizeChange = (e: React.ChangeEvent<HTMLSelectElement>) => {
    const newSize = parseInt(e.target.value);
    setPageSize(newSize);
    setCurrentPage(1); // 重置到第一页
  };
  
  // 重置筛选条件
  const resetFilters = () => {
    setFilterBuilding('');
    setFilterGender('');
    setFilterStatus('');
    setSearchTerm('');
    setCurrentPage(1);
  };

  // 组件挂载时获取数据
  useEffect(() => {
    fetchDormitories();
    fetchBuildings();
    fetchStudents();
  }, []);

  return (
    <div style={styles.container}>
      <div style={styles.header}>
        <h2 style={styles.title}>宿舍管理</h2>
        <button style={styles.addButton} onClick={showAddModal}>
          添加宿舍
        </button>
      </div>
      
      {/* 过滤控件 */}
      <div style={styles.filterContainer}>
        <div style={styles.filterRow}>
          <div style={styles.filterItem}>
            <label style={styles.filterLabel}>楼宇筛选：</label>
            <select 
              style={styles.filterSelect}
              value={filterBuilding}
              onChange={(e) => setFilterBuilding(e.target.value)}
            >
              <option value="">全部</option>
              {buildings.map(building => (
                <option key={building} value={building}>{building}</option>
              ))}
            </select>
          </div>
          
          <div style={styles.filterItem}>
            <label style={styles.filterLabel}>性别筛选：</label>
            <select 
              style={styles.filterSelect}
              value={filterGender}
              onChange={(e) => setFilterGender(e.target.value)}
            >
              <option value="">全部</option>
              <option value="男">男</option>
              <option value="女">女</option>
            </select>
          </div>
          
          <div style={styles.filterItem}>
            <label style={styles.filterLabel}>入住状态：</label>
            <select 
              style={styles.filterSelect}
              value={filterStatus}
              onChange={(e) => setFilterStatus(e.target.value)}
            >
              <option value="">全部</option>
              <option value="occupied">已入住</option>
              <option value="empty">空宿舍</option>
            </select>
          </div>
        </div>
        
        <div style={styles.filterRow}>
          <div style={styles.searchItem}>
            <input
              type="text"
              placeholder="搜索房间号或楼宇名称..."
              value={searchTerm}
              onChange={(e) => setSearchTerm(e.target.value)}
              style={styles.searchInput}
            />
            <button style={styles.resetButton} onClick={resetFilters}>
              重置
            </button>
          </div>
        </div>
      </div>
      
      {/* 表格 */}
      <div style={styles.tableContainer}>
        {loading ? (
          <div style={styles.loading}>加载中...</div>
        ) : (
          <table style={styles.table}>
            <thead style={styles.tableHead}>
              <tr>
                <th style={styles.tableHeader}>楼宇名称</th>
                <th style={styles.tableHeader}>房间号</th>
                <th style={styles.tableHeader}>性别</th>
                <th style={styles.tableHeader}>容量</th>
                <th style={styles.tableHeader}>当前人数</th>
                <th style={styles.tableHeader}>操作</th>
              </tr>
            </thead>
            <tbody>
              {paginatedDormitories.length > 0 ? (
                paginatedDormitories.map(dorm => (
                  <tr key={dorm.id} style={styles.tableRow}>
                    <td style={styles.tableCell}>{dorm.buildingName}</td>
                    <td style={styles.tableCell}>{dorm.roomNumber}</td>
                    <td style={styles.tableCell}>{dorm.gender}</td>
                    <td style={styles.tableCell}>{dorm.capacity}</td>
                    <td style={styles.tableCell}>{dorm.members.length}</td>
                    <td style={styles.tableCell}>
                      <button style={styles.editButton} onClick={() => showEditModal(dorm)}>
                        编辑
                      </button>
                      <button style={styles.memberButton} onClick={() => showMemberModal(dorm)}>
                        成员管理
                      </button>
                      <button style={styles.deleteButton} onClick={() => deleteDormitoryAction(dorm.id)}>
                        删除
                      </button>
                    </td>
                  </tr>
                ))
              ) : (
                <tr>
                  <td colSpan={6} style={styles.emptyTable}>
                    暂无符合条件的宿舍数据
                  </td>
                </tr>
              )}
            </tbody>
          </table>
        )}
      </div>
      
      {/* 宿舍编辑模态框 */}
      {isModalVisible && (
        <div style={styles.modalOverlay}>
          <div style={styles.modal}>
            <div style={styles.modalHeader}>
              <h3 style={styles.modalTitle}>{isEditMode ? '编辑宿舍' : '添加宿舍'}</h3>
              <button style={styles.closeButton} onClick={handleCancel}>
                ×
              </button>
            </div>
            <div style={styles.modalBody}>
              <form style={styles.form} onSubmit={handleSubmit}>
                <div style={styles.formGroup}>
                  <label style={styles.formLabel} htmlFor="buildingName">楼宇名称 *</label>
                  <select
                    id="buildingName"
                    name="buildingName"
                    value={formData.buildingName}
                    onChange={handleInputChange}
                    style={styles.formSelect}
                    required
                  >
                    {buildings.map(building => (
                      <option key={building} value={building}>{building}</option>
                    ))}
                  </select>
                  {formErrors.buildingName && <div style={styles.errorText}>{formErrors.buildingName}</div>}
                </div>
                
                <div style={styles.formGroup}>
                  <label style={styles.formLabel} htmlFor="roomNumber">房间号 *</label>
                  <input
                    id="roomNumber"
                    type="text"
                    name="roomNumber"
                    value={formData.roomNumber}
                    onChange={handleInputChange}
                    style={styles.formInput}
                    placeholder="请输入房间号"
                    required
                  />
                  {formErrors.roomNumber && <div style={styles.errorText}>{formErrors.roomNumber}</div>}
                </div>
                
                <div style={styles.formGroup}>
                  <label style={styles.formLabel} htmlFor="gender">性别 *</label>
                  <select
                    id="gender"
                    name="gender"
                    value={formData.gender}
                    onChange={handleInputChange}
                    style={styles.formSelect}
                    required
                  >
                    <option value="男">男</option>
                    <option value="女">女</option>
                  </select>
                </div>
                
                <div style={styles.formGroup}>
                  <label style={styles.formLabel} htmlFor="capacity">宿舍容量 *</label>
                  <input
                    id="capacity"
                    type="number"
                    name="capacity"
                    value={formData.capacity}
                    onChange={handleInputChange}
                    style={styles.formInput}
                    placeholder="请输入宿舍容量（最多8人）"
                    min="1"
                    max="8"
                    step="1"
                    required
                  />
                  {formErrors.capacity && <div style={styles.errorText}>{formErrors.capacity}</div>}
                </div>
                
                <div style={styles.formActions}>
                  <button type="button" style={styles.cancelButton} onClick={handleCancel}>
                    取消
                  </button>
                  <button type="submit" style={styles.submitButton}>
                    确定
                  </button>
                </div>
              </form>
            </div>
          </div>
        </div>
      )}
      
      {/* 成员管理模态框 */}
      
      {/* 分页控件 */}
      {paginatedDormitories.length > 0 && (
        <div style={styles.paginationContainer}>
          <div style={styles.paginationInfo}>
            共 {filteredDormitories.length} 条记录，每页显示
            <select 
              style={styles.pageSizeSelect}
              value={pageSize}
              onChange={handlePageSizeChange}
            >
              <option value={5}>5</option>
              <option value={10}>10</option>
              <option value={20}>20</option>
              <option value={50}>50</option>
            </select>
            条
          </div>
          
          <div style={styles.paginationControls}>
            <button 
              style={styles.pageButton}
              onClick={() => handlePageChange(currentPage - 1)}
              disabled={currentPage === 1}
            >
              上一页
            </button>
            
            {/* 页码按钮 */}
            {Array.from({ length: Math.min(5, totalPages) }, (_, i) => {
              let pageNum;
              if (totalPages <= 5) {
                pageNum = i + 1;
              } else if (currentPage <= 3) {
                pageNum = i + 1;
              } else if (currentPage >= totalPages - 2) {
                pageNum = totalPages - 4 + i;
              } else {
                pageNum = currentPage - 2 + i;
              }
              return (
                <button
                  key={pageNum}
                  style={{
                    ...styles.pageButton,
                    ...(currentPage === pageNum ? styles.currentPageButton : {})
                  }}
                  onClick={() => handlePageChange(pageNum)}
                >
                  {pageNum}
                </button>
              );
            })}
            
            <button 
              style={styles.pageButton}
              onClick={() => handlePageChange(currentPage + 1)}
              disabled={currentPage === totalPages}
            >
              下一页
            </button>
          </div>
        </div>
      )}
      {isMemberModalVisible && currentDormitory && (
        <div style={styles.modalOverlay}>
          <div style={styles.memberModal}>
            <div style={styles.modalHeader}>
              <h3 style={styles.modalTitle}>{currentDormitory.buildingName}-{currentDormitory.roomNumber} 成员管理</h3>
              <button style={styles.closeButton} onClick={handleCancel}>
                ×
              </button>
            </div>
            <div style={styles.modalBody}>
              {/* 按班级分配功能 */}
              <div style={styles.classAssignmentSection}>
                <h4 style={styles.memberSectionTitle}>按班级分配学生</h4>
                <div style={styles.classAssignmentContainer}>
                  <select 
                    style={styles.classSelect}
                    value={selectedClass || ''}
                    onChange={(e) => setSelectedClass(e.target.value)}
                  >
                    <option value="">请选择班级</option>
                    {uniqueClasses.map(className => (
                      <option key={className} value={className}>{className}</option>
                    ))}
                  </select>
                  <button 
                    style={styles.assignByClassButton}
                    onClick={() => selectedClass && assignStudentsByClass(selectedClass)}
                    disabled={!selectedClass || formData.members.length >= formData.capacity}
                  >
                    按班级分配
                  </button>
                </div>
              </div>
              
              <div style={styles.memberManagementContainer}>
                {/* 当前成员列表 */}
                <div style={styles.memberSection}>
                  <h4 style={styles.memberSectionTitle}>当前成员 ({formData.members.length}/{formData.capacity})</h4>
                  <div style={styles.memberList}>
                    {formData.members.map(member => (
                      <div key={member.studentId} style={styles.memberItem}>
                        <span>{member.name} ({member.studentId}) - {member.class}</span>
                        <button 
                          style={styles.removeMemberButton} 
                          onClick={() => removeStudentFromDormitory(member.studentId)}
                        >
                          移除
                        </button>
                      </div>
                    ))}
                    {formData.members.length === 0 && (
                      <div style={styles.emptyMemberList}>暂无成员</div>
                    )}
                  </div>
                </div>
                
                {/* 可用学生列表 */}
                <div style={styles.memberSection}>
                  <h4 style={styles.memberSectionTitle}>可选学生</h4>
                  <div style={styles.memberList}>
                    {availableStudents.map(student => (
                      <div key={student.studentId} style={styles.memberItem}>
                        <span>{student.name} ({student.studentId}) - {student.class}</span>
                        <button 
                          style={styles.addMemberButton} 
                          onClick={() => addStudentToDormitory(student)}
                          disabled={formData.members.length >= formData.capacity}
                        >
                          添加
                        </button>
                      </div>
                    ))}
                    {availableStudents.length === 0 && (
                      <div style={styles.emptyMemberList}>暂无可选学生</div>
                    )}
                  </div>
                </div>
              </div>
              
              {/* 值日表管理 */}
              <div style={styles.dutyScheduleSection}>
                <h4 style={styles.memberSectionTitle}>一周值日表</h4>
                <div style={styles.dutyScheduleTable}>
                  {Object.keys(formData.dutySchedule || {}).map(day => (
                    <div key={day} style={styles.dutyDayRow}>
                      <div style={styles.dutyDayLabel}>{day}</div>
                      <div style={styles.dutyStudentCheckboxes}>
                        {formData.members.map(member => (
                          <label key={`${day}-${member.studentId}`} style={styles.dutyCheckboxLabel}>
                            <input
                              type="checkbox"
                              checked={(formData.dutySchedule && formData.dutySchedule[day] && formData.dutySchedule[day].includes(member.studentId)) || false}
                              onChange={(e) => handleDutyScheduleChange(day, member.studentId, e.target.checked)}
                            />
                            <span>{member.name}</span>
                          </label>
                        ))}
                        {formData.members.length === 0 && (
                          <div style={styles.emptyDutyList}>请先添加成员</div>
                        )}
                      </div>
                    </div>
                  ))}
                </div>
              </div>
              
              <div style={styles.formActions}>
                <button type="button" style={styles.cancelButton} onClick={handleCancel}>
                  取消
                </button>
                <button type="button" style={styles.submitButton} onClick={saveMemberChanges}>
                  保存
                </button>
              </div>
            </div>
          </div>
        </div>
      )}
    </div>
  );
};

// 样式定义 - 整合为单一对象
const styles: Record<string, React.CSSProperties> = {
  container: {
    padding: '20px',
    fontFamily: '-apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, "Helvetica Neue", Arial, sans-serif',
  },
  header: {
    marginBottom: '20px',
    display: 'flex',
    justifyContent: 'space-between',
    alignItems: 'center',
  },
  title: {
    margin: 0,
    fontSize: '24px',
    fontWeight: 600,
    color: '#333',
  },
  addButton: {
    padding: '8px 16px',
    backgroundColor: '#1890ff',
    color: 'white',
    border: 'none',
    borderRadius: '4px',
    cursor: 'pointer',
    fontSize: '14px',
    transition: 'background-color 0.3s',
  },
  filterContainer: {
    marginBottom: '16px',
    padding: '12px',
    backgroundColor: '#f5f5f5',
    borderRadius: '4px',
  },
  filterRow: {
    display: 'flex',
    alignItems: 'center',
    marginBottom: '8px',
    gap: '16px',
  },
  filterItem: {
    display: 'flex',
    alignItems: 'center',
    gap: '8px',
  },
  searchItem: {
    display: 'flex',
    alignItems: 'center',
    gap: '12px',
    flex: 1,
  },
  searchInput: {
    flex: 1,
    padding: '8px 12px',
    border: '1px solid #d9d9d9',
    borderRadius: '4px',
    fontSize: '14px',
  },
  resetButton: {
    padding: '8px 16px',
    backgroundColor: '#666',
    color: 'white',
    border: 'none',
    borderRadius: '4px',
    cursor: 'pointer',
    fontSize: '14px',
  },
  filterLabel: {
    marginRight: '8px',
    fontSize: '14px',
    color: '#333',
  },
  filterSelect: {
    padding: '6px 12px',
    border: '1px solid #d9d9d9',
    borderRadius: '4px',
    fontSize: '14px',
  },
  tableContainer: {
    overflowX: 'auto',
    border: '1px solid #e8e8e8',
    borderRadius: '4px',
  },
  loading: {
    padding: '40px',
    textAlign: 'center',
    color: '#999',
  },
  table: {
    width: '100%',
    borderCollapse: 'collapse',
  },
  tableHead: {
    backgroundColor: '#fafafa',
  },
  tableHeader: {
    padding: '12px',
    textAlign: 'left',
    borderBottom: '1px solid #e8e8e8',
    fontWeight: 500,
    fontSize: '14px',
    color: '#333',
  },
  tableRow: {
    transition: 'background-color 0.3s',
  },
  tableCell: {
    padding: '12px',
    borderBottom: '1px solid #e8e8e8',
    fontSize: '14px',
    color: '#333',
  },
  emptyTable: {
    padding: '40px',
    textAlign: 'center',
    color: '#999',
    fontSize: '14px',
  },
  paginationContainer: {
    marginTop: '16px',
    padding: '12px',
    backgroundColor: '#f5f5f5',
    borderRadius: '4px',
    display: 'flex',
    justifyContent: 'space-between',
    alignItems: 'center',
  },
  paginationInfo: {
    fontSize: '14px',
    color: '#666',
    display: 'flex',
    alignItems: 'center',
    gap: '8px',
  },
  pageSizeSelect: {
    padding: '4px 8px',
    border: '1px solid #d9d9d9',
    borderRadius: '4px',
    fontSize: '14px',
  },
  paginationControls: {
    display: 'flex',
    alignItems: 'center',
    gap: '4px',
  },
  pageButton: {
    padding: '6px 12px',
    backgroundColor: 'white',
    color: '#333',
    border: '1px solid #d9d9d9',
    borderRadius: '4px',
    cursor: 'pointer',
    fontSize: '14px',
    minWidth: '32px',
  },
  currentPageButton: {
    backgroundColor: '#1890ff',
    color: 'white',
    borderColor: '#1890ff',
  },
  editButton: {
    padding: '4px 8px',
    backgroundColor: '#52c41a',
    color: 'white',
    border: 'none',
    borderRadius: '4px',
    cursor: 'pointer',
    fontSize: '12px',
    marginRight: '4px',
  },
  memberButton: {
    padding: '4px 8px',
    backgroundColor: '#722ed1',
    color: 'white',
    border: 'none',
    borderRadius: '4px',
    cursor: 'pointer',
    fontSize: '12px',
    marginRight: '4px',
  },
  deleteButton: {
    padding: '4px 8px',
    backgroundColor: '#ff4d4f',
    color: 'white',
    border: 'none',
    borderRadius: '4px',
    cursor: 'pointer',
    fontSize: '12px',
  },
  modalOverlay: {
    position: 'fixed',
    top: 0,
    left: 0,
    right: 0,
    bottom: 0,
    backgroundColor: 'rgba(0, 0, 0, 0.45)',
    display: 'flex',
    alignItems: 'center',
    justifyContent: 'center',
    zIndex: 1000,
  },
  modal: {
    width: '520px',
    backgroundColor: 'white',
    borderRadius: '8px',
    boxShadow: '0 4px 12px rgba(0, 0, 0, 0.15)',
  },
  memberModal: {
    width: '800px',
    maxHeight: '80vh',
    backgroundColor: 'white',
    borderRadius: '8px',
    boxShadow: '0 4px 12px rgba(0, 0, 0, 0.15)',
    overflowY: 'auto',
  },
  modalHeader: {
    padding: '16px 24px',
    borderBottom: '1px solid #f0f0f0',
    display: 'flex',
    justifyContent: 'space-between',
    alignItems: 'center',
  },
  modalTitle: {
    margin: 0,
    fontSize: '16px',
    fontWeight: 500,
    color: '#333',
  },
  closeButton: {
    background: 'none',
    border: 'none',
    fontSize: '20px',
    color: '#999',
    cursor: 'pointer',
    padding: 0,
    width: '24px',
    height: '24px',
    display: 'flex',
    alignItems: 'center',
    justifyContent: 'center',
  },
  modalBody: {
    padding: '24px',
  },
  form: {
    display: 'flex',
    flexDirection: 'column',
    gap: '16px',
  },
  formGroup: {
    display: 'flex',
    flexDirection: 'column',
    gap: '8px',
  },
  formLabel: {
    fontSize: '14px',
    fontWeight: 500,
    color: '#333',
  },
  formInput: {
    padding: '8px 12px',
    border: '1px solid #d9d9d9',
    borderRadius: '4px',
    fontSize: '14px',
    transition: 'border-color 0.3s',
  },
  formSelect: {
    padding: '8px 12px',
    border: '1px solid #d9d9d9',
    borderRadius: '4px',
    fontSize: '14px',
    transition: 'border-color 0.3s',
  },
  errorText: {
    color: '#ff4d4f',
    fontSize: '12px',
    marginTop: '4px',
  },
  formActions: {
    display: 'flex',
    justifyContent: 'flex-end',
    gap: '12px',
    marginTop: '8px',
  },
  cancelButton: {
    padding: '8px 16px',
    backgroundColor: 'white',
    color: '#333',
    border: '1px solid #d9d9d9',
    borderRadius: '4px',
    cursor: 'pointer',
    fontSize: '14px',
    transition: 'all 0.3s',
  },
  submitButton: {
    padding: '8px 16px',
    backgroundColor: '#1890ff',
    color: 'white',
    border: 'none',
    borderRadius: '4px',
    cursor: 'pointer',
    fontSize: '14px',
    transition: 'background-color 0.3s',
  },
  classAssignmentSection: {
    marginBottom: '24px',
    padding: '16px',
    backgroundColor: '#f5f5f5',
    borderRadius: '4px',
  },
  classAssignmentContainer: {
    display: 'flex',
    gap: '12px',
    alignItems: 'center',
  },
  classSelect: {
    padding: '8px 12px',
    border: '1px solid #d9d9d9',
    borderRadius: '4px',
    fontSize: '14px',
    minWidth: '150px',
  },
  assignByClassButton: {
    padding: '8px 16px',
    backgroundColor: '#722ed1',
    color: 'white',
    border: 'none',
    borderRadius: '4px',
    cursor: 'pointer',
    fontSize: '14px',
    transition: 'background-color 0.3s',
  },
  memberManagementContainer: {
    display: 'flex',
    gap: '24px',
    marginBottom: '24px',
  },
  memberSection: {
    flex: 1,
    display: 'flex',
    flexDirection: 'column',
    gap: '12px',
  },
  memberSectionTitle: {
    margin: 0,
    fontSize: '14px',
    fontWeight: 500,
    color: '#333',
  },
  memberList: {
    maxHeight: '300px',
    overflowY: 'auto',
    border: '1px solid #e8e8e8',
    borderRadius: '4px',
    padding: '8px',
  },
  memberItem: {
    display: 'flex',
    justifyContent: 'space-between',
    alignItems: 'center',
    padding: '8px',
    borderBottom: '1px solid #f0f0f0',
  },
  removeMemberButton: {
    padding: '2px 8px',
    backgroundColor: '#ff4d4f',
    color: 'white',
    border: 'none',
    borderRadius: '4px',
    cursor: 'pointer',
    fontSize: '12px',
  },
  addMemberButton: {
    padding: '2px 8px',
    backgroundColor: '#52c41a',
    color: 'white',
    border: 'none',
    borderRadius: '4px',
    cursor: 'pointer',
    fontSize: '12px',
  },
  emptyMemberList: {
    padding: '16px',
    textAlign: 'center',
    color: '#999',
    fontSize: '14px',
  },
  dutyScheduleSection: {
    marginBottom: '24px',
    padding: '16px',
    backgroundColor: '#f5f5f5',
    borderRadius: '4px',
  },
  dutyScheduleTable: {
    display: 'flex',
    flexDirection: 'column',
    gap: '12px',
  },
  dutyDayRow: {
    display: 'flex',
    alignItems: 'center',
    gap: '12px',
  },
  dutyDayLabel: {
    width: '80px',
    fontWeight: 500,
    color: '#333',
  },
  dutyStudentCheckboxes: {
    flex: 1,
    display: 'flex',
    flexWrap: 'wrap',
    gap: '8px',
  },
  dutyCheckboxLabel: {
    display: 'flex',
    alignItems: 'center',
    gap: '4px',
    padding: '4px 8px',
    backgroundColor: 'white',
    borderRadius: '4px',
    border: '1px solid #d9d9d9',
    cursor: 'pointer',
  },
  emptyDutyList: {
    color: '#999',
    fontSize: '14px',
  },
};

export default DormitoryManagement;